<template>
  <a-upload
    :action="uploadUrl"
    :headers="headers"
    :before-upload="beforeUpload"
    :max-count="maxCount"
    :disabled="disabled"
    list-type="picture-card"
    v-model:file-list="fileList"
    :data="uploadParams"
    :accept="accept"
    @change="handleChange"
    @preview="handlePreview"
  >
    <template #default>
      <slot>
        <div v-if="fileList.length < maxCount">
          <plus-outlined />
          <div style="margin-top: 8px">上传</div>
        </div>
      </slot>
    </template>
  </a-upload>
  <div class="upload-tip" v-if="tip">{{ tip }}</div>
  <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script setup lang="ts">
  // PICTURE("picture"),//图册图片
  // TEXT("text"),//图文图片
  // HONOR_TOP("honor_top"),//荣誉上
  // HONOR_MIDDLE("honor_middle"),//荣誉中
  // HONOR_BOTTOM("honor_bottom"),//荣誉下
  // CASE_CHARACTERISTICS("case_characteristics"),//案列特征
  // CASE_CASE("case_case"),//案列案列
  // PRODUCT_CHARACTERISTICS("product_characteristics"),//产品特征
  // PRODUCT_DETAILS("product_details"),//产品详情
  // EVENT("event"),//产品活动
  // CONTACT_US("contact_us"),//关于我们
  import { ref, defineProps, defineEmits, watch } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { uploadUrl } from '/@/api/common/api';

  const userStore = useUserStore();
  const props = defineProps({
    modelValue: { type: Array, default: () => [] },
    disabled: { type: Boolean, default: false },
    maxCount: { type: Number, default: 1 },
    action: { type: String, default: '' },
    beforeUpload: { type: Function, default: (file: File) => file.type.indexOf('image/') === 0 },
    tip: { type: String, default: '支持扩展名：.jpg, .png, .gif 等图片格式' },
    uploadParams: {
      type: Object,
      default: () => ({}),
    },
  });
  const emit = defineEmits(['update:modelValue', 'change', 'preview']);
  const accept = 'image/*';
  const headers = { 'X-Access-Token': userStore.getToken };
  const fileList = ref<any[]>(props.modelValue || []);

  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');

  function handleChange(info: any) {
    if (info.file.status === 'done' || info.file.status === 'removed') {
      uploadHandleChange(info);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败.`);
    }
  }
  function uploadHandleChange(info) {
    let fileList = info.fileList;
    fileList = fileList.map((file) => {
      if (file.response) {
        file = Object.assign(file.response.result, props.uploadParams);
      }
      return file;
    });
    // message.success(`${info.file.name} 文件上传成功`);
    console.log('info.fileList.result', fileList);
    emit('update:modelValue', fileList);
    previewVisible.value = false;
  }
  async function handlePreview(file: any) {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || (file.url ? file.url.substring(file.url.lastIndexOf('/') + 1) : '');
    emit('preview', file);
  }

  function handleCancel() {
    previewVisible.value = false;
    previewTitle.value = '';
  }

  function getBase64(file: File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  const setFileList = (value: any) => {
    console.log('value', value);
    fileList.value = value;
    fileList.value.forEach((item: any) => {
      item.thumbUrl = item.url;
    });
  };
  defineExpose({
    setFileList,
  });
</script>

<style scoped>
  .upload-tip {
    color: #888;
    font-size: 12px;
    margin-top: 4px;
  }
</style>
